package com.example.myapplication.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.Toolbar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapplication.ImgInfo.GridInfo;
import com.example.myapplication.ImgInfo.ImgInfo;
import com.example.myapplication.NewsInfo.NewsInfo;
import com.example.myapplication.NewsInfo.NewsType;
import com.example.myapplication.R;
import com.example.myapplication.utils.Config;
import com.example.myapplication.utils.HttpUtils;
import com.example.myapplication.utils.ImageUtils;
import com.example.myapplication.utils.MAdapter;
import com.example.myapplication.utils.MyServiceAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;

public class HomeFragment extends Fragment {

    private View view;
    private ImageView imageView;
    private ViewPager viewPager1, viewPager2;
    private EditText text;
    private Button btn;
    private TabLayout tabs;
    private GridView gridView;
    private RequestQueue quest;

    private List<GridInfo.Grid> gridInfos;
    public List<ImageView> imgList = new ArrayList<ImageView>();
    private List<NewsFragment> newsFragments = new ArrayList<NewsFragment>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    MyAdapter adapter = new MyAdapter();
                    viewPager1.setAdapter(adapter);
                    break;
                case 300:
                    gridView.setAdapter((MyServiceAdapter)msg.obj);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        InitView(view);
        ShowImages();
        ShowGrid();
        initNewsTab();
        return view;
    }

    //查找元素
    private void InitView(View view) {
        quest = Volley.newRequestQueue(getContext());
        viewPager1 = view.findViewById(R.id.images_viewp);
        viewPager2 = view.findViewById(R.id.tab_viewpa);
        btn = view.findViewById(R.id.se_btn);
        text = view.findViewById(R.id.nin_et);
        tabs = view.findViewById(R.id.tabs);
        gridView = view.findViewById(R.id.gridview_a);
        imageView = view.findViewById(R.id.none_img);
        viewPager2.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int code = newsType.get(position).getDictCode();
                initNewsDetail2(code,position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //轮播图
    private void ShowImages() {
        //请求图片路径
        String url = HttpUtils.UrlFactory("rotation/lists");
        //下载图片
        HttpUtils.Get(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {
                        String data = response.body().string();
                        ImgInfo imgInfo = new Gson().fromJson(data, ImgInfo.class);
                        for (int i = 0; i < imgInfo.getRows().size(); i++) {
                            String URl = Config.URL + imgInfo.getRows().get(i).getImgUrl();
                            ImageView imageView = new ImageView(getContext());
                            //图片自适应
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                            imgList.add(imageView);
                            Loadimg(imageView, URl, null);
                        }
                        handler.sendEmptyMessage(200);
                    }

                }

        );

    }

    //加载图片
    private List<Bitmap> Loadimg(@Nullable final ImageView imageView, String url, @Nullable final List<Bitmap> list) {
        final Bitmap map;
        ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                imageView.setImageBitmap(bitmap);
            }
        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.i("aaaaa", "报错了......" + volleyError.getMessage());
            }
        });
        quest.add(request);
        return list;
    }

    //适配器对象
    class MyAdapter extends PagerAdapter {
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            container.addView(imgList.get(position));
            return imgList.get(position);
        }

        public CharSequence getPageTitle(int position) {
            return super.getPageTitle(position);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        public int getCount() {
            return imgList.size();
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView(imgList.get(position));
        }
    }

    //展示grid列表
    private void ShowGrid() {
        HttpUtils.Get("service/list?pageNum=1&pageSize=5", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String data = response.body().string();
                GridInfo grid = new Gson().fromJson(data, GridInfo.class);
//                MAdapter<GridInfo.Grid> girdAdapter = new MAdapter<GridInfo.Grid>((ArrayList) grid.getRows(),R.layout.gird_service_item) {
//                    @Override
//                    public void bindView(ViewHolder holder,final GridInfo.Grid obj) {
//                        holder.setText(R.id.gird_item_name,obj.getServiceName());
//                        holder.setImageBitmap(R.id.gird_item_img,Config.URL + "/" + obj.getImgUrl(),quest);
//                    }
//                };
                MyServiceAdapter adapter = new MyServiceAdapter(grid.getRows(),getActivity(),quest);
                Message message = new Message();
                message.what = 300;
                message.obj = adapter;
                handler.sendMessage(message);
            }
        });
    }


    private List<NewsType.NewsTypeDetail> newsType = new ArrayList<>();
    private List<NewsInfo.NewsInfoDetail> newsInfos = new ArrayList<>();
    private void initNewsTab(){
        HttpUtils.Get("system/press_category", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String data = response.body().string();
                NewsType news = new Gson().fromJson(data, NewsType.class);
                newsType = news.getData();
                for (int i = 0; i < newsType.size(); i++){
                    initNewsDetail(newsType.get(i).getDictCode());
                }
                //回到主线程
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyNewsPageAdapter adapter = new MyNewsPageAdapter(getFragmentManager());
                        viewPager2.setAdapter(adapter);
                        tabs.setupWithViewPager(viewPager2);
                    }
                });
            }
        });
    }

    private void initNewsDetail2(int type, final int position){
        HttpUtils.Get("press/list?categoryId=" + type, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String data = response.body().string();
                NewsInfo info = new Gson().fromJson(data,NewsInfo.class);
                newsInfos = info.getRows();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        NewsFragment fragment2 = newsFragments.get(position);
                        fragment2.setNewsList(newsInfos);
                    }
                });

            }
        });
    }

    private void initNewsDetail(int type){
        HttpUtils.Get("press/list?categoryId=" + type, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String data = response.body().string();
                NewsInfo info = new Gson().fromJson(data,NewsInfo.class);
                newsInfos = info.getRows();
                NewsFragment fragment = new NewsFragment(newsInfos,quest);
                newsFragments.add(fragment);
            }
        });
    }

    class MyNewsPageAdapter extends FragmentPagerAdapter{
        public MyNewsPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return newsFragments.get(position);
        }

        @Override
        public int getCount() {
            return newsType.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return newsType.get(position).getDictLabel();
        }
    }

}
